package lifecycle

import (
	"syscall"
	"time"

	"gitee.com/chuanjinge/go-container/container/info"
	"gitee.com/chuanjinge/go-container/pkg"
)

// 停止容器的运行
func StopContainer(containerId string) error {
	// 找到容器ID对应的容器进程
	cInfo, err := info.GetContainerInfoByContainerId(containerId)
	if err != nil {
		return err
	}

	// kill发送SIGTERM信号给容器进程（父进程应该会捕捉子进程的退出）
	if err := syscall.Kill(cInfo.State.Pid, syscall.SIGTERM); err != nil {
		return err
	}

	RemoveContainerNetwork(containerId)

	// 修改容器信息文件的运行状态为false等等
	cInfo.State.Paused = true
	cInfo.State.Running = false
	cInfo.State.FinisededAt = time.Now()
	cInfo.HasBeenManuallyStopped = true

	pkg.InitLogConf(containerId)
	defer pkg.CloseLogConf()
	pkg.LogConf(cInfo)

	return nil
}
